/*
 * @Author: 13177709051 3506463075@qq.com
 * @Date: 2024-11-01 19:10:44
 * @LastEditors: 13177709051 3506463075@qq.com
 * @LastEditTime: 2024-11-01 19:46:19
 * @FilePath: /linux29/ringqueue/Main.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "RingQueue.hpp"
#include "Task.hpp"
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <ctime>

void *Consumer(void *args)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    while (true)
    {
        Task t;
        // 1. 消费
        rq->Pop(&t);
        //2. 处理数据
        t();
        std::cout << "Consumer->" << t.result() << std::endl;
    }
}

void *Productor(void *args)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);

    while(true)
    {
        sleep(1);
        //1. 构造数据
        int x = rand() % 10 + 1;//[1, 10]
        usleep(x * 1000);
        int y = rand() % 10 + 1;
        Task t(x, y);

        //2. 生产
        rq->Push(t);

        std::cout << "Productor ->" << t.debug() << std::endl;
    }
}

int main()
{
    srand(time(nullptr) ^ getpid());
    RingQueue<Task> *rq = new RingQueue<Task>(5);

    pthread_t c1, c2, p1, p2, p3;
    pthread_create(&c1, nullptr, Consumer, rq);
    pthread_create(&c2, nullptr, Consumer, rq);
    pthread_create(&p1, nullptr, Productor, rq);
    pthread_create(&p2, nullptr, Productor, rq);
    pthread_create(&p3, nullptr, Productor, rq);

    pthread_join(c1, nullptr);
    pthread_join(c2, nullptr);
    pthread_join(p1, nullptr);
    pthread_join(p2, nullptr);
    pthread_join(p3, nullptr);

    return 0;
}